<template>
  <basic-container>
    <el-row :gutter="24" class="organ-info">
      <el-col :span="6" style="padding-right: 0px;">
        <el-card class="border-card" shadow="never">
          <div slot="header" class="clearfix">
            <h4 class="el-card__title">组织机构树</h4>
            <el-button type="text"
                       icon="el-icon-circle-plus-outline"
                       size="small"
                       @click="handleAdd"
                       :disabled="addDisabled"
                       style="float: right;">新增
            </el-button>
          </div>
          <ul id="organTree" class="ztree" style="min-height: 580px; max-height:580px; overflow: auto"></ul>
        </el-card>
      </el-col>
      <el-col :span="18" style="padding-left: 0px;">
        <el-card class="border-card organ-list-card" shadow="never">
          <div slot="header">
            <h4 class="el-card__title">组织机构列表</h4>
            <div class="el-card__tool" @keyup.enter="querySearch">
              <el-input placeholder="请输入查询条件" size="mini" style="width:300px;" v-model="queryStream">
                <el-button slot="append" size="mini" icon="el-icon-search" @click="querySearch"></el-button>
              </el-input>
            </div>
          </div>
          <avue-crud ref="crud"
                     class="organ-list"
                     :option="option"
                     :data="data"
                     v-model="ruleForm"
                     :page="page"
                     @on-load="onLoad"
                     @row-save="rowSave"
                     @row-update="rowUpdate"
                     @current-change="currentChange"
                     @size-change="sizeChange"
                     style="min-height: 580px;">
            <template slot-scope="scope" slot="menu">
              <el-button type="text"
                         icon="el-icon-edit"
                         size="small"
                         @click.stop="rowEdit(scope.row, scope.index)">编辑
              </el-button>
              <el-button type="text"
                         icon="el-icon-delete"
                         size="small"
                         v-if="scope.row.childCount <= 1"
                         @click="rowDel(scope.row,scope.index)">删除
              </el-button>
            </template>
          </avue-crud>
        </el-card>
      </el-col>
    </el-row>
  </basic-container>
</template>
<script>
  import $ from 'jquery'
  import { organTree, getList, verifyUnique, add, update, remove } from "@/api/organ/organ";
  import { socialCodeRule } from '@/util/validate'

  const DIC = {
    TYPE: [{
      label: '类别',
      value: '1'
    }, {
      label: '单位',
      value: '2'
    }, {
      label: '部门',
      value: '3'
    }, {
      label: '临时',
      value: '9'
    }],
  }
  export default {
    name: "organ-info",
    inheritAttrs: false,
    data() {
      const formatType = (row, value, label, column) => {
        if (value == '1') {
          return "类别"
        } else if (value == '2') {
          return "单位"
        } else if (value == '3') {
          return "部门"
        }
        return "临时"
      };
      const validCode = (rule, value, callback) => {
        let data = {value: value};
        if (this.ruleForm.id) {
          data = {value: value, id: this.ruleForm.id};
        }
        verifyUnique(data).then(data => {
          if (!data.success)
            callback(new Error('此组织编码已被使用!'))
          else
            callback()
        })
          .catch(err => {
            console.log(err)
            callback(new Error('验证失败!'))
          })
      };
      return {
        addDisabled: true,
        treeData: [],
        setting: {
          view: {
            showIcon: false
          },
          data: {
            key: {
              name: "title"
            },
            simpleData: {
              enable: true,
              idKey: "id",
              pIdKey: "parentId",
              rootPId: "",
              nodeType: "type",
              regionId: "regionId",
              regionName: "regionName"
            }
          },
          // async: {
          //   enable: true,
          //   autoParam: ["id", "type"],
          //   type: "post",
          //   dataType: "json",
          //   url: ""
          // },
          callback: {
            onClick: this.zTreeOnClick,
            // onExpand: this.zTreeOnExpand
          }
        },
        zTree: {},
        queryStream: '',
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          border: true,
          tree: true,
          addBtn: false,
          columnBtn: false,
          refreshBtn: false,
          searchBtn: false,
          editBtn: false,
          delBtn: false,
          index: true,
          indexLabel: '序号',
          size: 'small',
          // dialogHeight: 350,
          menuWidth: 160,
          column: [
            {
              label: "组织编码",
              prop: "code",
              search: false,
              maxlength: 32,
              rules: [
                {required: true, message: '请输入组织编码', trigger: 'blur'},
                {min: 3, max: 32, message: '长度在 3 到 32 个字符'},
                {pattern: /^[a-zA-Z0-9_]{3,32}$/, message: '请输入3-32个字符，允许输入字母、数字、下划线'},
                {validator: validCode, trigger: 'blur'}
              ]
            },
            {
              label: "组织名称",
              prop: "name",
              search: false,
              rules: [
                {required: true, message: '请输入组织名称', trigger: 'blur'},
                {min: 2, max: 128, message: '长度在 2 到 128 个字符'}
              ]
            },
            {
              label: "组织类型",
              prop: "type",
              type: "radio",
              dicData: DIC.TYPE,
              formatter: formatType,
              search: false,
              span: 24,
              rules: [
                {required: true, message: '请选择组织类型', trigger: 'blur'},
              ]
            },
            {
              label: "组织简码",
              prop: "shortCode",
              search: false,
              hide: true,
              maxlength: 16,
              rules: [
                {min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur'}
              ]
            },
            {
              label: "组织简称",
              prop: "shortName",
              search: false,
              hide: true,
              rules: [
                {min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur'}
              ]
            },
            {
              label: "",
              prop: "regionId",
              hide: true,
              display: false,
            },
            {
              label: "所属区划",
              prop: "regionName",
              disabled: true
            },
            {
              label: "",
              prop: "parentId",
              hide: true,
              display: false,
            },
            {
              label: "上级组织",
              prop: "parentName",
              hide: true,
              disabled: true
            },
            {
              label: "统一社会信用代码",
              prop: "socialCode",
              search: false,
              hide: true,
              maxlength: 18,
              rules: [
                {min: 18, max: 18, message: '请输入18位统一社会信用代码'},
                {validator: socialCodeRule, trigger: 'blur' },
              ]
            },
            {
              label: "排序",
              prop: "sortOrder",
              type: 'number',
              span: 8,
              search: false,
              hide: true,
              value: 1,
              minRows: 1,
              maxRows: 999
            },
            {
              label: "组织说明",
              prop: "remark",
              type: "textarea",
              search: false,
              hide: true,
              minWidth: '200',
              span: 24,
              minRows: 3
            },
          ]
        },
        data: [],
        ruleForm: {},
      }
    },
    created() {
      this.getOrganTree();
    },
    methods: {
      getOrganTree() {
        this.treeData = [];
        this.addDisabled = true;
        organTree().then(res => {
          this.treeData = res.data;
          $.fn.zTree.init($("#organTree"), this.setting, this.treeData);
          this.zTree = $.fn.zTree.getZTreeObj("organTree");
          if (this.query.nodeId) {
            this.addDisabled = false;
            var node = this.zTree.getNodeByParam("id", this.query.nodeId);
            if (node) {
              this.zTree.selectNode(node);
              this.zTree.expandNode(node, true, false);
            }
          }
        });
      },
      handleAdd() {
        if (this.zTree.getNodes().length > 0 && !this.query.nodeId) {
          this.$message({
            type: "error",
            message: "请先选择上级区划或组织"
          });
          return;
        }
        if (this.query.nodeType !== '0') {
          const idIndex = this.$refs.crud.findColumnIndex("parentId");
          this.option.column[idIndex].value = this.query.nodeId;
          const nameIndex = this.$refs.crud.findColumnIndex("parentName");
          this.option.column[nameIndex].value = this.query.nodeName;
        }
        const rgidIndex = this.$refs.crud.findColumnIndex("regionId");
        this.option.column[rgidIndex].value = this.query.regionId;
        const rgnameIndex = this.$refs.crud.findColumnIndex("regionName");
        this.option.column[rgnameIndex].value = this.query.regionName;
        const typeIndex = this.$refs.crud.findColumnIndex("type");
        if (this.query.nodeType == '0') {
          this.option.column[typeIndex].value = '1';
          this.option.column[typeIndex].disabled = true;
        } else if (this.query.nodeType == '1') {
          this.option.column[typeIndex].value = '2';
          this.option.column[typeIndex].disabled = true;
        } else {
          this.option.column[typeIndex].value = '3';
          this.option.column[typeIndex].disabled = false;
        }
        this.$refs.crud.rowAdd();
      },
      zTreeOnClick(event, treeId, treeNode) {
        this.handleNodeClick(treeNode);
      },
      // zTreeOnExpand(event, treeId, treeNode) {
      //   this.addNodes(treeNode);
      // },
      // async addNodes(treeNode) {
      //
      // },
      onLoad(page, params = {}) {
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data;
          this.page.total = data.total;
          this.data = data.records;
        });
      },
      handleNodeClick(treeNode) {
        this.queryStream = '';
        this.query.nodeId = treeNode.id;
        this.query.nodeName = treeNode.title;
        this.query.nodeType = treeNode.type;
        this.query.regionId = treeNode.regionId;
        this.query.regionName = treeNode.regionName;
        this.query.query = "";
        this.page.currentPage = 1;
        this.addDisabled = false;
        this.onLoad(this.page, this.query);
      },
      rowSave(row, loading, done) {
        add(this.ruleForm).then(ret => {
          if (ret.success) {
            loading();
            this.getOrganTree();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            done();
            this.$message({
              type: "error",
              message: ret.msg
            });
          }
        }, error => {
          done();
          console.log(error);
        })
      },
      rowEdit(row, index) {
        const typeIndex = this.$refs.crud.findColumnIndex("type");
        this.option.column[typeIndex].disabled = true;
        this.$refs.crud.rowEdit(row, index);
      },
      rowUpdate(row, index, loading, done) {
        update(this.ruleForm).then(ret => {
          if (ret.success) {
            loading();
            this.getOrganTree();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            done();
            this.$message({
              type: "error",
              message: ret.msg
            });
          }
        }, error => {
          done();
          console.log(error);
        });
      },
      rowDel(row, index) {
        this.$confirm("确定要删除该组织吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row);
          })
          .then(ret => {
            if (ret.success) {
              this.getOrganTree();
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }).catch(() => {
        });
      },

      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      querySearch() {
        this.query.query = this.queryStream;
        this.page.currentPage = 1;
        this.onLoad(this.page, this.query);
      },
    }
  }
</script>
<style scoped lang="scss">
  @import "~_s/placeholders";
  @import '~_s/table-list';
  ::v-deep .organ-list {
    @extend %fullsize;
    @extend %table-list;
    .avue-crud__menu {
      display: none;
    }
  }
  ::v-deep .organ-info {
    .el-card {
      .el-card__header {
        padding: 5px 15px;
      }
      .el-card__title {
        font-size: 14px;
      }
    }
  }

</style>